<template>
	<PageTemplate title="我的">
    <template #default>
      <view class="profile-content">
        <!-- 个人信息区域 -->
        <view class="profile-card">
          <view class="user-info-section">
            <view class="avatar-wrapper" @click="changeAvatar">
              <image class="avatar" :src="userInfo.avatar" mode="aspectFill"></image>
              <view class="camera-overlay">
                <text class="camera-icon">📷</text>
              </view>
            </view>
            <view class="user-text-info">
              <view class="username-row">
                <text class="username">{{ userInfo.name || '未登录' }}</text>
                <image 
                  v-if="systemNotificationStore.systemUnreadCount > 0"
                  class="notification-icon"
                  src="/static/profile/i-new.png"
                  @click="showNotificationList = true"
                ></image>
                <image 
                  v-else
                  class="notification-icon"
                  src="/static/profile/i-new-none.png"
                  @click="showNotificationList = true"
                ></image>
              </view>
              <text class="account">@{{ userInfo.account || userInfo.username || 'username' }}</text>
              <text v-if="userInfo.signature" class="signature">{{ userInfo.signature }}</text>
              <view class="status-actions">
                <view class="status-badge">
                  <text class="status-dot"></text>
                  <text class="status-text">在线</text>
                </view>
                <view class="action-buttons" v-if="isLoggedIn">
                  <button class="action-btn logout-btn" @click="handleLogout">
                    <text class="btn-text">退出</text>
                  </button>
                </view>
              </view>
            </view>
          </view>
          
          <view class="action-buttons" v-if="!isLoggedIn">
            <button class="action-btn login-btn" @click="goToAuth">
              <text class="btn-text">登录 / 注册</text>
            </button>
          </view>
        </view>
        
        <!-- 联系人列表 -->
        <ContactList v-if="isLoggedIn" />
      </view>
      
      <!-- 通知列表弹窗 -->
      <NotificationList 
        :show="showNotificationList" 
        @update:show="showNotificationList = $event"
      />
    </template>
  </PageTemplate>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { logout, updateUserInfo } from '@/api/user/index'
import { uploadFile } from '@/utils/upload'
import { showToast, getUserInfo, showModal, navigateTo } from '@/utils/index'
import PageHeader from '@/components/PageHeader.vue';
import PageTemplate from '@/components/PageTemplate.vue';
import ContactList from '@/components/ContactList.vue';
import NotificationList from '@/components/NotificationList.vue';
import websocket from '@/utils/websocket'
import { usePrivateChatStore } from '@/stores/privateChat'
import { useSystemNotificationStore } from '@/stores/system_notification'
const privateChatStore = usePrivateChatStore()
const systemNotificationStore = useSystemNotificationStore()

// 用户信息
const userInfo = reactive({
	name: '',
	signature: '',
	avatar: '',
	user_id: 0,
	username: '',
	account: '' // 添加 account 字段
})

// 是否已登录
const isLoggedIn = ref(false)

// 通知列表显示状态
const showNotificationList = ref(false)

// 跳转到登录注册页面
const goToAuth = () => {
  navigateTo('/pages/auth/auth', 'reLaunch')
}

// 更换头像
const changeAvatar = async () => {
	if (!isLoggedIn.value) {
		showToast('请先登录')
		return
	}
	
	// 选择图片
	uni.chooseImage({
		count: 1,
		sizeType: ['compressed'],
		sourceType: ['album', 'camera'],
		success: async (res) => {
			const tempFilePath = res.tempFilePaths[0]
			
			try {
				// 显示上传进度
				uni.showLoading({
					title: '上传中...'
				})
				
				// 上传文件
				const uploadResult = await uploadFile(tempFilePath)
				
				// 隐藏加载提示
				uni.hideLoading()
				
				// 检查上传结果
				console.log('Upload result:', uploadResult)
				
				if (uploadResult.code === 200) {
					// 获取上传文件的ID和URL
					const uploadId = uploadResult.data.upload_id
					const avatarUrl = uploadResult.data.fileurl
					
					if (!uploadId || !avatarUrl) {
						throw new Error('上传成功但未返回完整信息')
					}
					
					// 更新用户头像
					const updateResult = await updateUserInfo({
						user_id: userInfo.user_id,
						avatar: avatarUrl,
						avatar_upload_id: uploadId
					})
					
					console.log('Update result:', updateResult)
					
					if (updateResult.code === 200) {
						// 更新本地用户信息
						userInfo.avatar = avatarUrl
						const storedUserInfo = getUserInfo()
						if (storedUserInfo) {
							storedUserInfo.avatar = avatarUrl
							uni.setStorageSync('userInfo', storedUserInfo)
						}
						
						showToast('头像更新成功', 'success')
					}
				}
			} catch (error: any) {
				console.error('更换头像失败:', error)
				uni.hideLoading()
			}
		},
		fail: (err) => {
			console.error('选择图片失败:', err)
			showToast('取消选择')
		}
	})
}

// 处理退出登录
const handleLogout = async () => {
	const confirm = await showModal('提示', '确定要退出登录吗？')
	if (confirm) {
		// 调用后端退出登录接口
		logout().then((res: any) => {
			handleLogoutSuccess()
		}).catch((error) => {
			// 即使后端调用失败，也清除本地状态
			handleLogoutSuccess()
		})
	}
}

// 退出登录成功处理
const handleLogoutSuccess = () => {
  // 关闭 WebSocket 连接（标记为手动关闭，不再重连）
  websocket.close(true);

	// 清除用户信息
	userInfo.name = ''
	userInfo.signature = ''
	userInfo.avatar = ''
	userInfo.user_id = 0
	userInfo.username = ''
	userInfo.account = ''
	isLoggedIn.value = false
	
	// 清除本地存储的用户信息
	uni.removeStorageSync('userInfo')

  // 清除本地存储的token
	uni.removeStorageSync('token')
  
  // 清空私聊数据 销毁store实例
  privateChatStore.clearPrivateChats()
  privateChatStore.$dispose()

  // 清空系统通知数据 销毁store实例
  systemNotificationStore.clearNotifications()
  systemNotificationStore.$dispose()
	
	// 跳转到登录页面
  goToAuth()
}

// 页面显示时检查登录状态
onMounted(() => {
	// 从本地存储获取用户信息
	const storedUserInfo = getUserInfo()
	if (storedUserInfo) {
		userInfo.name = storedUserInfo.name
		userInfo.signature = storedUserInfo.signature
		userInfo.avatar = storedUserInfo.avatar
		userInfo.user_id = storedUserInfo.user_id
		userInfo.username = storedUserInfo.username
		userInfo.account = storedUserInfo.account || storedUserInfo.username // 兼容处理
		isLoggedIn.value = true
	}
})

// 页面加载时执行
onMounted(() => {
	// 初始化操作
})
</script>

<style scoped>
.profile-content {
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

.profile-card {
  display: flex;
  flex-direction: column;
  padding: 50rpx 40rpx;
  background: linear-gradient(135deg, #ffffff 0%, #fcfdff 100%);
  border-radius: 24rpx;
  margin: 0 30rpx;
  box-shadow: 0 12rpx 30rpx rgba(0, 0, 0, 0.06);
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
}

.profile-card::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 8rpx;
  background: linear-gradient(90deg, #007aff, #00c874, #ff6b6b);
  border-radius: 24rpx 24rpx 0 0;
}

.user-info-section {
  display: flex;
  align-items: center;
  width: 100%;
}

.avatar-wrapper {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  overflow: visible;
  position: relative;
  border: 4rpx solid rgba(255, 255, 255, 0.8);
  box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.12);
  margin-right: 30rpx;
  flex-shrink: 0;
  transition: transform 0.2s ease;
}

.avatar-wrapper:active {
  transform: scale(0.95);
}

.avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

.camera-overlay {
  position: absolute;
  right: -10rpx;
  bottom: -10rpx;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 50%;
  width: 46rpx;
  height: 46rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.2);
  z-index: 2;
  transition: all 0.3s ease;
  border: 4rpx solid #ffffff;
}

.avatar-wrapper:hover .camera-overlay {
  transform: scale(1.1) rotate(10deg);
  box-shadow: 0 6rpx 15rpx rgba(0, 0, 0, 0.3);
}

.camera-icon {
  font-size: 20rpx;
  color: #007aff;
  filter: drop-shadow(0 0 2rpx rgba(0, 122, 255, 0.3));
}

.user-text-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.username-row {
  display: flex;
  align-items: center;
  margin-bottom: 8rpx;
}

.username {
  font-size: 36rpx;
  font-weight: 600;
  color: #2c3e50;
  display: block;
  letter-spacing: 0.5rpx;
}

.notification-icon {
  width: 20px;
  height: 20px;
  margin-left: 20rpx;
}

.account {
  font-size: 26rpx;
  color: #7f8c8d;
  margin-bottom: 8rpx;
}

.signature {
  font-size: 24rpx;
  color: #95a5a6;
  margin-bottom: 16rpx;
  line-height: 1.4;
}

.status-actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.status-badge {
  display: flex;
  align-items: center;
  background-color: #e8f4ff;
  padding: 8rpx 22rpx;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 10rpx rgba(0, 122, 255, 0.1);
}

.status-dot {
  width: 14rpx;
  height: 14rpx;
  background-color: #00c874;
  border-radius: 50%;
  margin-right: 10rpx;
  box-shadow: 0 0 6rpx rgba(0, 200, 116, 0.5);
}

.status-text {
  font-size: 22rpx;
  color: #007aff;
  font-weight: 500;
}

.action-buttons {
  margin-left: 20rpx;
}

.action-btn {
  width: auto;
  min-width: 100rpx;
  height: 52rpx;
  border-radius: 26rpx;
  font-size: 24rpx;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  transition: all 0.3s ease;
  padding: 0 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
}

.login-btn {
  background: linear-gradient(90deg, #007aff, #00c874);
  color: #fff;
}

.logout-btn {
  background: #f8f9fa;
  color: #ff3b30;
}

.btn-text {
  font-weight: 500;
  letter-spacing: 0.5rpx;
}

.action-btn:active {
  transform: scale(0.96);
}
</style>